package com.example.basicdemo.controller;


import com.alibaba.fastjson.JSONObject;
import com.example.basicdemo.model.DemoBaseResult;
import com.example.basicdemo.model.domain.RegisterAppDomain;
import com.example.basicdemo.model.domain.RegisterAppKeyReq;
import com.isyscore.os.dev.config.IsyscoreConfigProperties;
import com.isyscore.os.dev.config.IsyscoreConstants;
import com.isyscore.os.dev.util.TokenUtils;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api/${api-module}/demo")
public class DemoController {

    @Autowired
    private OkHttpClient okHttpClient;

    @Autowired
    private IsyscoreConfigProperties isyscoreConfigProperties;


    /**
     * 应用注册
     * 纯前端
     * 纯后端
     * 桌面菜单应用
     * 后台应用
     * 外联应用
     * 应用卸载
     * 注册应用公私钥
     * 获取accessToken
     */
    @GetMapping("registerFrontApp")
    public DemoBaseResult registerFrontApp() throws Exception {
        RegisterAppDomain appInfo = new RegisterAppDomain();
        appInfo.setCode("basic-demo-register-xyz123");
        appInfo.setName("纯前端应用");
        appInfo.setIntroduction("这是一个纯前端应用的注册demo");
        appInfo.setVersion("v1.0.0.0");
        appInfo.setVersionIntroduction("这是一个初始化版本");
        //状态定义, 注册时启用
        appInfo.setStatus(1);
        //显示菜单定义
        appInfo.setInMenu(1);
        //三方应用定义
        appInfo.setType(3);
        //业务应用定义, 不包含后端服务的应用
        appInfo.setSecondType(5);
        JSONObject extend = new JSONObject();
        extend.put("field", "value");
        appInfo.setExtend(JSONObject.toJSONString(extend));
        RequestBody body = RequestBody.create(JSONObject.toJSONString(appInfo), MediaType.get("application/json; charset=utf-8"));
        Request request = new Request.Builder().url(isyscoreConfigProperties.getRegisterAppUrl() + IsyscoreConstants.REGISTER_APP_URI)
                .post(body)
                .header("isc-tenant-id", "superTenant")
                .header("isc-api-version", "2.1").build();
        okhttp3.Response response = okHttpClient.newCall(request).execute();
        if (response.isSuccessful()) {
            String bodyString = response.body().string();
            if (!StringUtils.isEmpty(bodyString)) {
                JSONObject resultJson = JSONObject.parseObject(bodyString);
                resultJson.put("message", "您已成功注册应用");
                DemoBaseResult.Data data = new DemoBaseResult.Data()
                        .setParam(JSONObject.parseObject(JSONObject.toJSONString(appInfo)))
                        .setResult(resultJson);
                return new DemoBaseResult().setData(data);
            }
        }
        return new DemoBaseResult();
    }

    @GetMapping("registerBackEndApp")
    public DemoBaseResult registerBackEndApp() throws Exception {
        RegisterAppDomain appInfo = new RegisterAppDomain();
        appInfo.setCode("basic-demo-register-xyz123");
        appInfo.setName("纯后端应用");
        appInfo.setIntroduction("这是一个纯后端应用的注册demo");
        appInfo.setVersion("v1.0.0.0");
        appInfo.setVersionIntroduction("这是一个初始化版本");
        //状态定义, 注册时启用
        appInfo.setStatus(1);
        //不显示菜单定义
        appInfo.setInMenu(2);
        //三方应用定义
        appInfo.setType(3);
        //业务应用定义, 至少包含后端服务的应用
        appInfo.setSecondType(3);
        JSONObject extend = new JSONObject();
        extend.put("field", "value");
        appInfo.setExtend(JSONObject.toJSONString(extend));
        RequestBody body = RequestBody.create(JSONObject.toJSONString(appInfo), MediaType.get("application/json; charset=utf-8"));
        Request request = new Request.Builder().url(isyscoreConfigProperties.getRegisterAppUrl() + IsyscoreConstants.REGISTER_APP_URI)
                .post(body)
                .header("isc-tenant-id", "superTenant")
                .header("isc-api-version", "2.1").build();
        okhttp3.Response response = okHttpClient.newCall(request).execute();
        if (response.isSuccessful()) {
            String bodyString = response.body().string();
            if (!StringUtils.isEmpty(bodyString)) {
                JSONObject resultJson = JSONObject.parseObject(bodyString);
                resultJson.put("message", "您已成功注册应用");
                DemoBaseResult.Data data = new DemoBaseResult.Data()
                        .setParam(JSONObject.parseObject(JSONObject.toJSONString(appInfo)))
                        .setResult(resultJson);
                return new DemoBaseResult().setData(data);
            }
        }
        return new DemoBaseResult();
    }

    @GetMapping("registerMenuApp")
    public DemoBaseResult registerMenuApp() throws Exception {
        RegisterAppDomain appInfo = new RegisterAppDomain();
        appInfo.setCode("basic-demo-register-xyz123");
        appInfo.setName("桌面菜单应用");
        appInfo.setIntroduction("这是一个桌面菜单应用的注册demo, 顾名思义, 桌面菜单应用是指其入口会出现在桌面, 关键字段是inMenu; " +
                "此处仅是模拟注册, 因为OS应用的运行机制, 该应用的定义是包含后端服务, 需要成功安装完成后, OS才会认可其真实存在性, 才会出现在桌面菜单, 请知悉.");
        appInfo.setVersion("v1.0.0.0");
        appInfo.setVersionIntroduction("这是一个初始化版本");
        //状态定义, 注册时启用
        appInfo.setStatus(1);
        //显示菜单定义
        appInfo.setInMenu(1);
        //三方应用定义
        appInfo.setType(3);
        //业务应用定义, 至少包含后端服务的应用
        appInfo.setSecondType(3);
        //功能菜单接口指定, 接入功能权限所必须
        appInfo.setAclReturnUrl("http://basic-demo-xyz123-service-svc:8857/api/app/basic-demo-xyz123/demo/acl");
        JSONObject extend = new JSONObject();
        extend.put("field", "value");
        appInfo.setExtend(JSONObject.toJSONString(extend));
//        appInfo.setRedirectUrl("https://open.isyscore.com/");
        RequestBody body = RequestBody.create(JSONObject.toJSONString(appInfo), MediaType.get("application/json; charset=utf-8"));
        Request request = new Request.Builder().url(isyscoreConfigProperties.getRegisterAppUrl() + IsyscoreConstants.REGISTER_APP_URI)
                .post(body)
                .header("isc-tenant-id", "superTenant")
                .header("isc-api-version", "2.1").build();
        okhttp3.Response response = okHttpClient.newCall(request).execute();
        if (response.isSuccessful()) {
            String bodyString = response.body().string();
            if (!StringUtils.isEmpty(bodyString)) {
                JSONObject resultJson = JSONObject.parseObject(bodyString);
                resultJson.put("message", "您已成功注册应用");
                DemoBaseResult.Data data = new DemoBaseResult.Data()
                        .setParam(JSONObject.parseObject(JSONObject.toJSONString(appInfo)))
                        .setResult(resultJson);
                return new DemoBaseResult().setData(data);
            }
        }
        return new DemoBaseResult();
    }

    @GetMapping("registerBackgroundApp")
    public DemoBaseResult registerBackgroundApp() throws Exception {
        RegisterAppDomain appInfo = new RegisterAppDomain();
        appInfo.setCode("basic-demo-register-xyz123");
        appInfo.setName("后台应用");
        appInfo.setIntroduction("这是一个后台应用的注册demo");
        appInfo.setVersion("v1.0.0.0");
        appInfo.setVersionIntroduction("这是一个初始化版本");
        //状态定义, 注册时启用
        appInfo.setStatus(1);
        //不显示菜单定义
        appInfo.setInMenu(2);
        //三方应用定义
        appInfo.setType(3);
        //业务应用定义, 至少包含后端服务的应用
        appInfo.setSecondType(3);
        JSONObject extend = new JSONObject();
        extend.put("field", "value");
        appInfo.setExtend(JSONObject.toJSONString(extend));
        RequestBody body = RequestBody.create(JSONObject.toJSONString(appInfo), MediaType.get("application/json; charset=utf-8"));
        Request request = new Request.Builder().url(isyscoreConfigProperties.getRegisterAppUrl() + IsyscoreConstants.REGISTER_APP_URI)
                .post(body)
                .header("isc-tenant-id", "superTenant")
                .header("isc-api-version", "2.1").build();
        okhttp3.Response response = okHttpClient.newCall(request).execute();
        if (response.isSuccessful()) {
            String bodyString = response.body().string();
            if (!StringUtils.isEmpty(bodyString)) {
                JSONObject resultJson = JSONObject.parseObject(bodyString);
                resultJson.put("message", "您已成功注册应用");
                DemoBaseResult.Data data = new DemoBaseResult.Data()
                        .setParam(JSONObject.parseObject(JSONObject.toJSONString(appInfo)))
                        .setResult(resultJson);
                return new DemoBaseResult().setData(data);
            }
        }
        return new DemoBaseResult();
    }

    @GetMapping("registerOutApp")
    public DemoBaseResult registerOutApp() throws Exception {
        RegisterAppDomain appInfo = new RegisterAppDomain();
        appInfo.setCode("basic-demo-register-xyz123");
        appInfo.setName("外联应用");
        appInfo.setIntroduction("这是一个外联应用的注册demo, 外联应用不归OS管理, 仅在桌面菜单提供应用入口");
        appInfo.setVersion("v1.0.0.0");
        appInfo.setVersionIntroduction("这是一个初始化版本");
        //状态定义, 注册时启用
        appInfo.setStatus(1);
        //显示菜单定义
        appInfo.setInMenu(1);
        //外联应用定义
        appInfo.setType(5);
        //业务应用定义, 不包含后端服务的应用
        appInfo.setSecondType(5);
        JSONObject extend = new JSONObject();
        extend.put("field", "value");
        appInfo.setExtend(JSONObject.toJSONString(extend));
        //定义跳转路径
        appInfo.setRedirectUrl("https://open.isyscore.com/");
        RequestBody body = RequestBody.create(JSONObject.toJSONString(appInfo), MediaType.get("application/json; charset=utf-8"));
        Request request = new Request.Builder().url(isyscoreConfigProperties.getRegisterAppUrl() + IsyscoreConstants.REGISTER_APP_URI)
                .post(body)
                .header("isc-tenant-id", "superTenant")
                .header("isc-api-version", "2.1").build();
        okhttp3.Response response = okHttpClient.newCall(request).execute();
        if (response.isSuccessful()) {
            String bodyString = response.body().string();
            if (!StringUtils.isEmpty(bodyString)) {
                JSONObject resultJson = JSONObject.parseObject(bodyString);
                resultJson.put("message", "您已成功注册应用");
                DemoBaseResult.Data data = new DemoBaseResult.Data()
                        .setParam(JSONObject.parseObject(JSONObject.toJSONString(appInfo)))
                        .setResult(resultJson);
                return new DemoBaseResult().setData(data);
            }
        }
        return new DemoBaseResult();
    }

    @GetMapping("registerLightApp")
    public DemoBaseResult registerLightApp() throws Exception {
        RegisterAppDomain appInfo = new RegisterAppDomain();
        appInfo.setCode("basic-demo-register-xyz123");
        appInfo.setName("轻应用");
        appInfo.setIntroduction("这是一个轻应用的注册demo");
        appInfo.setVersion("v1.0.0.0");
        appInfo.setVersionIntroduction("这是一个初始化版本");
        //状态定义, 注册时启用
        appInfo.setStatus(1);
        //显示菜单定义
        appInfo.setInMenu(1);
        //轻应用定义
        appInfo.setType(6);
        //业务应用定义, 不包含后端服务的应用
        appInfo.setSecondType(5);
        JSONObject extend = new JSONObject();
        extend.put("field", "value");
        appInfo.setExtend(JSONObject.toJSONString(extend));
        //定义跳转路径
        appInfo.setRedirectUrl("https://open.isyscore.com/");
        RequestBody body = RequestBody.create(JSONObject.toJSONString(appInfo), MediaType.get("application/json; charset=utf-8"));
        Request request = new Request.Builder().url(isyscoreConfigProperties.getRegisterAppUrl() + IsyscoreConstants.REGISTER_APP_URI)
                .post(body)
                .header("isc-tenant-id", "superTenant")
                .header("isc-api-version", "2.1").build();
        okhttp3.Response response = okHttpClient.newCall(request).execute();
        if (response.isSuccessful()) {
            String bodyString = response.body().string();
            if (!StringUtils.isEmpty(bodyString)) {
                JSONObject resultJson = JSONObject.parseObject(bodyString);
                resultJson.put("message", "您已成功注册应用");
                DemoBaseResult.Data data = new DemoBaseResult.Data()
                        .setParam(JSONObject.parseObject(JSONObject.toJSONString(appInfo)))
                        .setResult(resultJson);
                return new DemoBaseResult().setData(data);
            }
        }
        return new DemoBaseResult();
    }

    @GetMapping("deleteApp")
    public DemoBaseResult deleteApp() throws Exception {
        // 清理demo应用
        Request request = new Request.Builder().url(isyscoreConfigProperties.getRegisterAppUrl() + "/api/rc-application/application/delete?code=basic-demo-register-xyz123")
                .delete()
                .header("isc-tenant-id", "superTenant")
                .header("token", TokenUtils.getLoginToken())
                .header("isc-api-version", "2.1").build();
        okhttp3.Response response = okHttpClient.newCall(request).execute();
        if (response.isSuccessful()) {
            String body = response.body().string();
            if (!StringUtils.isEmpty(body)) {
                JSONObject resultJson = JSONObject.parseObject(body);
                resultJson.put("message", "您已成功删除应用");
                DemoBaseResult.Data data = new DemoBaseResult.Data()
                        .setResult(resultJson);
                return new DemoBaseResult().setData(data);
            }
        }
        return new DemoBaseResult();
    }

    /**
     * 公钥字符串
     */
    private static String publicKey = "";

    @GetMapping("registerAppKey")
    public DemoBaseResult registerAppKey() throws Exception {
        RegisterAppKeyReq registerAppKeyReq = new RegisterAppKeyReq();
        registerAppKeyReq.setAppCode("basic-demo-xyz123");
        registerAppKeyReq.setPermission(new ArrayList<>());
        RequestBody body = RequestBody.create(JSONObject.toJSONString(registerAppKeyReq), MediaType.get("application/json; charset=utf-8"));
        Request request = new Request.Builder().url(isyscoreConfigProperties.getRegisterAppUrl() + "/api/app/operation-center/monitoring/dev/param/registerAppKey")
                .post(body)
                .header("token", token)
                .build();
        okhttp3.Response response = okHttpClient.newCall(request).execute();
        if (response.isSuccessful()) {
            String bodyString = response.body().string();
            if (!StringUtils.isEmpty(bodyString)) {
                JSONObject resultJson = JSONObject.parseObject(bodyString);
                resultJson.put("message", "您已成功公私钥");
                publicKey = resultJson.getString("data");
                DemoBaseResult.Data data = new DemoBaseResult.Data()
                        .setParam(JSONObject.parseObject(JSONObject.toJSONString(registerAppKeyReq)))
                        .setResult(resultJson);
                return new DemoBaseResult().setData(data);
            }
        }
        return new DemoBaseResult();
    }

    @GetMapping("getAccessToken")
    public DemoBaseResult getAccessToken() throws Exception {
        Map<String, String> param = new HashMap<>(8);
        param.put("publicKey", publicKey);
        RequestBody body = RequestBody.create(JSONObject.toJSONString(param), MediaType.get("application/json; charset=utf-8"));
        Request request = new Request.Builder().url(isyscoreConfigProperties.getRegisterAppUrl() + "/api/core/authorization/auth/accessToken")
                .post(body)
                .header("token", token)
                .build();
        okhttp3.Response response = okHttpClient.newCall(request).execute();
        if (response.isSuccessful()) {
            String bodyString = response.body().string();
            if (!StringUtils.isEmpty(bodyString)) {
                JSONObject resultJson = JSONObject.parseObject(bodyString);
                resultJson.put("message", "您已成功获取访问令牌");
                DemoBaseResult.Data data = new DemoBaseResult.Data()
                        .setParam(JSONObject.parseObject(JSONObject.toJSONString(param)))
                        .setResult(resultJson);
                return new DemoBaseResult().setData(data);
            }
        }
        return new DemoBaseResult();
    }


}
